import { createRouter, createWebHashHistory } from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import pinia from '/@/stores/index';
import { storeToRefs } from 'pinia';
import { useKeepALiveNames } from '/@/stores/keepAliveNames';
import { useRoutesList } from '/@/stores/routesList';
import { useThemeConfig } from '/@/stores/themeConfig';
import { Session } from '/@/utils/storage';
import { staticRoutes, notFoundAndNoPower } from '/@/router/route';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { useUserInfo } from '/@/stores/userInfo';

/**
 * 1、前端控制路由时：isRequestRoutes 为 false，需要写 roles，需要走 setFilterRoute 方法。
 * 2、后端控制路由时：isRequestRoutes 为 true，不需要写 roles，不需要走 setFilterRoute 方法），
 * 相关方法已拆解到对应的 `backEnd.ts` 与 `frontEnd.ts`（他们互不影响，不需要同时改 2 个文件）。
 * 特别说明：
 * 1、前端控制：路由菜单由前端去写（无菜单管理界面，有角色管理界面），角色管理中有 roles 属性，需返回到 userInfo 中。
 * 2、后端控制：路由菜单由后端返回（有菜单管理界面、有角色管理界面）
 */

// 读取后端控制路由配置
const storesThemeConfig = useThemeConfig(pinia);
const { themeConfig } = storeToRefs(storesThemeConfig);
const { isRequestRoutes } = themeConfig.value;

export const router = createRouter({
  history: createWebHashHistory(),
  routes: [...notFoundAndNoPower, ...staticRoutes],
});

// 路由扁平化处理
export function formatFlatteningRoutes(arr: any) {
  if (arr.length <= 0) return false;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children) {
      arr = arr.slice(0, i + 1).concat(arr[i].children, arr.slice(i + 1));
    }
  }
  return arr;
}

// 路由嵌套处理
export function formatTwoStageRoutes(arr: any) {
  if (arr.length <= 0) return false;
  const newArr: any = [];
  const cacheList: Array<string> = [];
  arr.forEach((v: any) => {
    if (v.path === '/') {
      newArr.push({ component: v.component, name: v.name, path: v.path, redirect: v.redirect, meta: v.meta, children: [] });
    } else {
      if (v.path.indexOf('/:') > -1) {
        v.meta['isDynamic'] = true;
        v.meta['isDynamicPath'] = v.path;
      }
      newArr[0].children.push({ ...v });
      if (newArr[0].meta.isKeepAlive && v.meta.isKeepAlive) {
        cacheList.push(v.name);
        const stores = useKeepALiveNames(pinia);
        stores.setCacheKeepAlive(cacheList);
      }
    }
  });
  return newArr;
}

// 路由导航守卫
router.beforeEach(async (to, from, next) => {
  NProgress.configure({ showSpinner: false });
  if (to.meta.title) NProgress.start();

  const userStore = useUserInfo(pinia);
  const { userInfo } = storeToRefs(userStore);
  const isAuthenticated = Session.get('isAuthenticated');

  // ========== 状态一致性检查 ==========
  const storedLocked = localStorage.getItem('isLocked') === 'true';
  const storedPath = localStorage.getItem('attemptedPath');

  // 如果未登录但有锁屏状态，清除锁屏状态
  if (!isAuthenticated && storedLocked) {
    localStorage.removeItem('isLocked');
    localStorage.removeItem('attemptedPath');
  }

  // 如果已登录但用户信息为空，且处于锁屏状态，也清除锁屏状态
  if (isAuthenticated && (!userInfo.value?.id) && storedLocked) {
    localStorage.removeItem('isLocked');
    localStorage.removeItem('attemptedPath');
  }
  // ========== 状态一致性检查结束 ==========

  // ========== 登录状态检查 ==========
  // 未登录处理
  if (!isAuthenticated) {
    // 清除可能的残留锁屏状态
    localStorage.removeItem('isLocked');
    localStorage.removeItem('attemptedPath');

    // 如果访问锁屏页，跳转到登录页
    if (to.path === '/lock') {
      next(`/login?redirect=${from.path || '/'}&params=${JSON.stringify(to.query || to.params)}`);
      NProgress.done();
      return;
    }

    if (to.path === '/login') {
      next();
    } else {
      next(`/login?redirect=${to.path}&params=${JSON.stringify(to.query || to.params)}`);
    }
    NProgress.done();
    return;
  }

  // 已登录但用户信息为空：重新获取
  const uid = userInfo.value?.id || '';
  if (isAuthenticated && !uid) {
    try {
      await userStore.getUserInfo();
    } catch (error) {
      console.error('获取用户信息失败:', error);
      Session.remove('isAuthenticated');
      localStorage.removeItem('isLocked');
      localStorage.removeItem('attemptedPath');
      next(`/login?redirect=${to.path}`);
      NProgress.done();
      return;
    }
  }

  // 已登录访问登录页：跳首页
  if (to.path === '/login') {
    next('/');
    NProgress.done();
    return;
  }

  // ========== 锁屏状态检查 ==========
  const isLocked = localStorage.getItem('isLocked') === 'true';
  const attemptedPath = localStorage.getItem('attemptedPath');

  // 已锁屏且访问非锁屏页：保存路径并跳转到锁屏页
  if (isLocked && to.path !== '/lock') {
    // 仅在没有存储路径时保存，避免覆盖已有有效路径
    if (to.path && !['/lock', '/lock-screen'].includes(to.path) && !attemptedPath) {
      localStorage.setItem('attemptedPath', to.fullPath);
    }
    next('/lock');
    NProgress.done();
    return;
  }

  // 访问锁屏页：如果是已锁屏状态允许访问，如果是未锁屏状态则跳回原路径
  if (to.path === '/lock') {
    if (!isLocked && attemptedPath) {
      // 未锁屏但访问锁屏页：跳转到存储的路径
      const tempPath = attemptedPath;
      localStorage.removeItem('attemptedPath');
      next(tempPath);
      NProgress.done();
      return;
    } else if (!isLocked && !attemptedPath) {
      // 未锁屏且无存储路径：跳转到首页
      next('/');
      NProgress.done();
      return;
    }
    // 已锁屏状态：允许停留在锁屏页
    next();
    NProgress.done();
    return;
  }

  // 未锁屏但有存储路径：跳转后清除路径
  if (!isLocked && attemptedPath) {
    const tempPath = attemptedPath;
    localStorage.removeItem('attemptedPath');
    next(tempPath);
    NProgress.done();
    return;
  }
  // ========== 锁屏检查修复结束 ==========

  const routesStore = useRoutesList(pinia);
  const { routesList } = storeToRefs(routesStore);

  // 获取第一个有效路由
  const getFirstValidRoute = () => {
    const findFirst = (routes: any[]): string => {
      for (const route of routes) {
        if (route.path && route.component) {
          return route.path;
        }
        if (route.children && route.children.length > 0) {
          const childFirst = findFirst(route.children);
          if (childFirst) return childFirst;
        }
      }
      return '';
    };
    return findFirst(routesList.value) || '/401';
  };

  // 动态路由未加载：初始化路由
  if (routesList.value.length === 0) {
    try {
      let initResult: { isNoPower: boolean; firstValidRoute?: string } = { isNoPower: false };
      if (isRequestRoutes) {
        const backEndResult = await initBackEndControlRoutes();
        if (typeof backEndResult === 'boolean') {
          initResult.isNoPower = backEndResult;
          initResult.firstValidRoute = getFirstValidRoute();
        } else {
          initResult = backEndResult;
        }
      } else {
        await initFrontEndControlRoutes();
        initResult.firstValidRoute = getFirstValidRoute();
      }

      if (initResult.isNoPower) {
        next('/401');
      } else {
        const firstValidRoute = initResult.firstValidRoute || getFirstValidRoute();
        const isRouteExist = router.getRoutes().some(route => route.path === to.path);

        // 关键修复：确保路由存在后再跳转
        if (isRouteExist) {
          next({ path: to.path, query: to.query, replace: true });
        } else {
          next({ path: firstValidRoute, replace: true });
        }
      }
    } catch (error) {
      console.error('路由初始化错误:', error);
      next('/404');
    } finally {
      NProgress.done();
    }
  } else {
    const isRouteExist = router.getRoutes().some(route => route.path === to.path);
    if (isRouteExist) {
      next();
    } else {
      const firstValidRoute = getFirstValidRoute();
      next({ path: firstValidRoute, replace: true });
    }
  }

  if (to.meta.title) {
    NProgress.done();
  }
});

// 路由后置守卫
router.afterEach(() => {
  NProgress.done();
});

export default router;